package eu.codlab.game.gameba.nonem.input;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

public abstract class AbstractButtonServer extends AsyncTask<Integer, Object, Object>{
	static AbstractButtonListener _listener;
	static ServerSocket _server_socket;
	static Handler _handler;
	static Socket _client;
	static DataOutputStream _out_to_lient;
	static BufferedReader _in_from_lient;
	static int _port;

	public boolean isCreated(){
		return _server_socket != null;
	}

	public void createSocket(){
		_client = null;
		if(_server_socket == null){
			try {
				_server_socket = new ServerSocket(_port);
				_server_socket.setReuseAddress(true);
				_server_socket.setSoTimeout(160000);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void destroy(){
		Log.d("AbstractButtonServer","destroy");
		try{
			if(_client != null){
				if(_client.isConnected())
					_client.close();
				if(!_client.isInputShutdown())
					_client.shutdownInput();
				if(!_client.isOutputShutdown())
					_client.shutdownOutput();
			}
			_client = null;
			_out_to_lient = null;
			_in_from_lient = null;
			_server_socket.close();
		}catch(Exception e){
		}
	}

	private AbstractButtonServer() {
	}

	protected AbstractButtonServer(AbstractButtonListener listener){
		this();
		_listener = listener;
		_handler = new Handler();
	}

	@Override
	protected Object doInBackground(Integer... params) {
		Log.d("AbstractButtonServer","AbstractButtonServer");
		if(!this.isCreated())
			createSocket();

		_port =params[0];
		destroy();
		_handler.post(new Thread(){
			public void run(){

				Log.d("AbstractButtonServer","watiClient");
				try {
					_client = _server_socket.accept();
					_out_to_lient = new DataOutputStream(_client.getOutputStream());
					_in_from_lient = new BufferedReader(new InputStreamReader(_client.getInputStream()));

					while(true){
						Log.d("AbstractButtonServer","waitData");
						boolean state = false;
						try{
							char tmp[]=new char [4];
							if(_in_from_lient.read(tmp) == 4){
								int cmd = tmp[0] + tmp[1]<<8;
								int key_state = tmp[2] & 1;
								_listener.onKeyFromClient(AbstractButtonServer.this, cmd, key_state);
							}
							state = true;
						} catch (Exception e) {
							e.printStackTrace();
							destroy();
						}

						if(state == true){
						}
					}
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});
		return null;
	}


}
